import { Upload } from '@x-tech/fe-puma-lib-upload';
// import XCMessageMgr from './XCMessageMgr';
//一个上传的类 支持批量上传
export default class XCUpLoader {

    private uplIns = new Upload(window.XCConfig.VUE_APP_ENV);
    private OBSResultQueue = new Queue<OBSResultInfo>();
    public ComResultQueue = new Queue<BaseResultInfo>();  //最终的上传结果
    private onEnd: Function | null = null;
    public totalNeedUpload = 0;
    private isStop = false;
    public processInfo = new ProcessInfo();
    private onPerUploadAction: Function | null = null;  //每上传一个文件后事件

    //提供上传结果统计
    public get UploadResult() {
        const data = this.ComResultQueue.data;
        const succssList :BaseResultInfo[]= [];
        const errorList :BaseResultInfo[] = [];
        data.forEach((item) => {
            item.isSuccess?succssList.push(item):errorList.push(item);
        })
        const isAllSuccess = errorList.length === 0;
        return {
            succssList,
            errorList,
            isAllSuccess
        }
    }
    private obsTimer: any = null;
    private async uploadToObs(files: File[]) {

        this.totalNeedUpload = files.length;
        const queueFiles = new Queue<File>(files);
        console.log('queueFiles',queueFiles);
        if (this.obsTimer) {
            clearInterval(this.obsTimer)
        }
        this.obsTimer = setInterval(async () => {
            const result = new OBSResultInfo();
            const file: any = queueFiles.deQueue();
            if(!file) return false;
            console.log('curfile',file);
            if (this.isStop) {
                clearInterval(this.obsTimer)
                throw new Error('停止上传obs');
            }
            try {           
                result.fileId = file.lastModified;
                result.fileName = file.name;
                const res = await this.uplIns.uploadWithoutFilename(file, false);
                result.isSuccess = true;
                result.resUrl = res;
            } catch (error) {
                result.isSuccess = false;
                result.errorDes = "上传obs:失败" + error as string;
            }
            this.OBSResultQueue.enQueue(result);
        }, 200)
    }

    private timer: any = null;
    //上传一个文件到obs 大致需要0.2s
    private uploadToXc(uploadFun: (res: OBSResultInfo) => Promise<{ isSuccess: boolean, error: string }>) {

        let isUploading = false;
        this.timer = setInterval(async () => {
            if (isUploading) return;

            const obsResult = this.OBSResultQueue.deQueue();
            // console.log("obsResult",obsResult);
            if (obsResult) {
                const commonResult = obsResult.copy();
                this.ComResultQueue.enQueue(commonResult);
                if (obsResult.isSuccess) {
                    //  上传至XC       
                    isUploading = true;
                    const result = await uploadFun(obsResult);
                    console.log('xc---result:', result);
                    isUploading = false;
                    //更换上传结果信息
                    commonResult.errorDes = result.error;
                    commonResult.isSuccess = result.isSuccess;
                } else {
                    //如果上传obs失败了 就不用更换上传结果信息 结果信息就是obs的结果信息
                }
                this.processInfo.percent = this.ComResultQueue.Length / this.totalNeedUpload;
                this.onPerUploadAction && this.onPerUploadAction();
                if (this.ComResultQueue.Length >= this.totalNeedUpload) {
                    this.stopUpload();
                }
            }
        }, 200);
    }

    //对外提供接口
    startUploadTask(files: File[], uploadFun: (res: OBSResultInfo) => Promise<{ isSuccess: boolean, error: string }>, onEnd: Function,
        onPerUploadAction: Function) {
        this.reset();
        this.onEnd = onEnd;
        this.onPerUploadAction = onPerUploadAction;
        this.uploadToObs(files);
        this.uploadToXc(uploadFun);
    }
    async upload2Obs(file: File) {
        return await this.uplIns.uploadWithoutFilename(file, false);
    }
    stopUpload() {
        if (this.timer) {
            console.log('stop');
            clearInterval(this.timer);
        }
        if (this.onEnd) {
            this.onEnd();
            this.onEnd = null;
        }
        this.isStop = true;
    }
    reset() {
        this.isStop = false;
        this.OBSResultQueue.clear();
        this.ComResultQueue.clear();
    }
}
//文件上传结果信息
export class BaseResultInfo {
    constructor(
        public fileId = 0,
        public fileName = '',
        public isSuccess: boolean = false,
        public errorDes = ''
    ) { }
    copy() {
        return new BaseResultInfo(this.fileId, this.fileName, this.isSuccess, this.errorDes)
    }
}
export class OBSResultInfo extends BaseResultInfo {
    resUrl = '';
}
class XCResultInfo extends BaseResultInfo {

}

//实时上传结果，对外返回
export class ProcessInfo {
    percent = 0;
}
//实现一个自己的队列  push - shift
class Queue<T> {
    private queue: T[] = [];
    constructor(array: T[] = []) {
        this.queue = array;
    }
    get Length() {
        return this.queue.length;
    }
    get data() {
        return this.queue;
    }
    enQueue(data: T) {
        if (data == null) {
            return;
        }
        this.queue.push(data)
    }
    deQueue() {
        if (this.queue.length === 0) {
            return
        }
        const data = this.queue.shift()
        return data
    }
    clear() {
        this.queue = [];
    }

}
